import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../../../models/upload_progress_record.dart';
import 'package:photo_manager/photo_manager.dart';

/// 上传进度管理服务
/// 负责管理相册上传进度，支持断点续传
class UploadProgressService {
  // 单例模式
  static final UploadProgressService _instance =
      UploadProgressService._internal();
  factory UploadProgressService() => _instance;
  UploadProgressService._internal();

  // 数据库实例
  Database? _database;

  // 数据库名称和版本
  static const String _databaseName = 'upload_progress.db';
  static const int _databaseVersion = 1;

  // 表名
  static const String _tableName = 'upload_progress_records';

  // 内存缓存，提高频繁访问的性能
  final Map<String, UploadProgressRecord> _progressCache = {};

  /// 获取数据库实例（如果不存在则创建）
  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await _initDatabase();
    return _database!;
  }

  /// 初始化数据库
  Future<Database> _initDatabase() async {
    try {
      // 获取数据库文件路径
      final documentsDirectory = await getApplicationDocumentsDirectory();
      final path = join(documentsDirectory.path, _databaseName);

      debugPrint('初始化上传进度数据库，路径: $path');

      // 打开数据库
      return await openDatabase(
        path,
        version: _databaseVersion,
        onCreate: (db, version) async {
          // 创建表结构
          await UploadProgressRecord.createTable(db);
          debugPrint('成功创建上传进度记录表');
        },
        onUpgrade: (db, oldVersion, newVersion) async {
          // 数据库升级逻辑（后续版本可能需要）
          debugPrint('数据库升级: $oldVersion -> $newVersion');
        },
      );
    } catch (e) {
      debugPrint('初始化上传进度数据库失败: $e');
      rethrow;
    }
  }

  /// 关闭数据库连接
  Future<void> close() async {
    final db = _database;
    if (db != null) {
      await db.close();
      _database = null;
      debugPrint('已关闭上传进度数据库连接');
    }
  }

  /// 获取相册记录
  Future<UploadProgressRecord?> getAlbum(String albumId) async {
    try {
      // 跳过处理"未知相册"
      if (albumId.isEmpty || albumId == '未知' || albumId == 'unknown') {
        debugPrint('尝试获取无效相册ID，已跳过: $albumId');
        return null;
      }

      // 检查缓存
      if (_progressCache.containsKey(albumId)) {
        return _progressCache[albumId];
      }

      // 从数据库查询
      final db = await database;
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'album_id = ?',
        whereArgs: [albumId],
      );

      if (maps.isNotEmpty) {
        final record = UploadProgressRecord.fromMap(maps.first);
        // 添加到缓存
        _progressCache[albumId] = record;
        return record;
      }
    } catch (e) {
      debugPrint('获取相册进度记录失败: $e');
    }

    return null;
  }

  /// 获取所有未完成的相册进度记录
  Future<List<UploadProgressRecord>> getIncompleteAlbums() async {
    try {
      final db = await database;
      final results = await db.query(
        _tableName,
        where: 'is_completed = ?',
        whereArgs: [0], // 0表示未完成
        orderBy: 'update_time DESC', // 按更新时间降序排列
      );

      final records =
          results.map((map) => UploadProgressRecord.fromMap(map)).toList();

      // 更新缓存
      for (var record in records) {
        _progressCache[record.albumId] = record;
      }

      return records;
    } catch (e) {
      debugPrint('获取未完成相册列表失败: $e');
      return [];
    }
  }

  /// 更新相册上传进度
  Future<void> updateAlbumProgress({
    required String albumId,
    required String albumName,
    required int processedCount,
    required String? lastAssetId,
  }) async {
    try {
      // 跳过处理"未知相册"
      if (albumName == '未知相册' ||
          albumId.isEmpty ||
          albumId == '未知' ||
          albumId == 'unknown') {
        debugPrint('跳过"未知相册"的进度更新: $albumId');
        return;
      }

      // 获取现有记录
      final existingRecord = await getAlbum(albumId);

      if (existingRecord == null) {
        // 记录不存在，创建新记录
        final record = UploadProgressRecord(
          id: null, // 自动生成
          albumId: albumId,
          albumName: albumName,
          processedCount: processedCount,
          lastAssetId: lastAssetId,
          updateTime: DateTime.now().millisecondsSinceEpoch,
          isCompleted: false,
        );

        // 插入数据库
        final db = await database;
        final id = await db.insert(_tableName, record.toMap());

        // 更新缓存
        record.id = id;
        _progressCache[albumId] = record;

        debugPrint('已创建相册[$albumName]的上传进度记录: $processedCount');
      } else {
        // 更新现有记录
        final updatedRecord = UploadProgressRecord(
          id: existingRecord.id,
          albumId: albumId,
          albumName: albumName,
          processedCount: processedCount,
          lastAssetId: lastAssetId ?? existingRecord.lastAssetId,
          updateTime: DateTime.now().millisecondsSinceEpoch,
          isCompleted: existingRecord.isCompleted,
        );

        // 更新数据库
        final db = await database;
        await db.update(
          _tableName,
          updatedRecord.toMap(),
          where: 'id = ?',
          whereArgs: [updatedRecord.id],
        );

        // 更新缓存
        _progressCache[albumId] = updatedRecord;

        debugPrint('已更新相册[$albumName]的上传进度: $processedCount');
      }
    } catch (e) {
      debugPrint('更新相册进度失败: $e');
    }
  }

  /// 标记相册上传完成
  Future<void> markAlbumCompleted(String albumId) async {
    try {
      final db = await database;

      // 获取现有记录
      final record = await getAlbum(albumId);

      if (record != null) {
        // 标记为已完成
        record.markAsCompleted();
        await db.update(
          _tableName,
          record.toMap(),
          where: 'id = ?',
          whereArgs: [record.id],
        );

        // 更新缓存
        _progressCache[albumId] = record;
        debugPrint('已标记相册[${record.albumName}]的上传为已完成');
      }
    } catch (e) {
      debugPrint('标记相册上传完成失败: $e');
    }
  }

  /// 重置相册上传进度
  Future<void> resetAlbumProgress(String albumId) async {
    try {
      final db = await database;

      // 获取现有记录
      final record = await getAlbum(albumId);

      if (record != null) {
        // 重置进度
        record.processedCount = 0;
        record.lastAssetId = null;
        record.isCompleted = false;
        record.updateTime = DateTime.now().millisecondsSinceEpoch;

        await db.update(
          _tableName,
          record.toMap(),
          where: 'id = ?',
          whereArgs: [record.id],
        );

        // 更新缓存
        _progressCache[albumId] = record;
        debugPrint('已重置相册[${record.albumName}]的上传进度');
      }
    } catch (e) {
      debugPrint('重置相册上传进度失败: $e');
    }
  }

  /// 删除相册上传进度记录
  Future<void> deleteAlbumProgress(String albumId) async {
    try {
      final db = await database;

      await db.delete(_tableName, where: 'album_id = ?', whereArgs: [albumId]);

      // 从缓存中移除
      _progressCache.remove(albumId);
      debugPrint('已删除相册[$albumId]的上传进度记录');
    } catch (e) {
      debugPrint('删除相册上传进度失败: $e');
    }
  }

  /// 清除所有进度记录
  Future<void> clearAllProgress() async {
    try {
      final db = await database;
      await db.delete(_tableName);

      // 清空缓存
      _progressCache.clear();
      debugPrint('已清除所有相册上传进度记录');
    } catch (e) {
      debugPrint('清除所有上传进度失败: $e');
    }
  }

  /// 清理所有"未知相册"的记录
  Future<void> cleanupUnknownAlbums() async {
    try {
      final db = await database;
      final deletedCount = await db.delete(
        _tableName,
        where: 'album_name = ?',
        whereArgs: ['未知相册'],
      );

      // 从缓存中移除
      _progressCache.removeWhere((_, record) => record.albumName == '未知相册');

      debugPrint('已删除$deletedCount个未知相册的上传进度记录');
    } catch (e) {
      debugPrint('清理未知相册记录失败: $e');
    }
  }

  /// 获取所有已完成的相册ID
  Future<List<String>> getCompletedAlbumIds() async {
    try {
      final db = await database;
      final results = await db.query(
        _tableName,
        columns: ['album_id'],
        where: 'is_completed = ?',
        whereArgs: [1], // 1表示已完成
      );

      return results.map((map) => map['album_id'] as String).toList();
    } catch (e) {
      debugPrint('获取已完成相册ID列表失败: $e');
      return [];
    }
  }

  /// 获取相册已处理的资产数量
  Future<int> getAlbumProcessedCount(String albumId) async {
    final record = await getAlbum(albumId);
    return record?.processedCount ?? 0;
  }

  /// 检查相册是否已完成上传
  Future<bool> isAlbumCompleted(String albumId) async {
    final record = await getAlbum(albumId);
    return record?.isCompleted ?? false;
  }

  /// 删除所有进度记录
  Future<void> deleteAllProgress() async {
    try {
      final db = await database;

      // 从数据库中删除所有记录
      final count = await db.delete(_tableName);

      // 清除内存缓存
      _progressCache.clear();

      debugPrint('已删除所有上传进度记录: $count 个');
    } catch (e) {
      debugPrint('删除所有上传进度记录失败: $e');
      rethrow;
    }
  }
}
